﻿using Microsoft.Phone.Info;
using Microsoft.Phone.Tasks;
using Q42.WinRT.Data;
using SpaceNeedle.SDK.Windows.Platform;
using SpaceNeedle.SDK.Windows.Platform.Commands;
using SpaceNeedle.SDK.Windows.Platform.Data;
using SpaceNeedle.SDK.Windows.Platform.Events;
using SpaceNeedle.x6473.WindowsPhone.Common;
using SpaceNeedle.x6473.WindowsPhone.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace SpaceNeedle.x6473.WindowsPhone.ViewModels
{
    public class HomeViewModel : GlobalViewModel
    {
        public event RawEventHandler RatingRequested = delegate { };

        public HomeViewModel() :base()
        {
            this.DialCommand = new RelayCommand(Dial);
            this.SettingsCommand = new RelayCommand(Settings);
            this.AboutShareCommand = new RelayCommand(AboutShare);
            this.NewRequestCommand = new RelayCommand(NewRequest);
            this.NewRequestCategorySelectedCommand = new RelayCommand(NewRequestCategorySelected);
            this.CallsCommand = new RelayCommand(Calls);
            this.CallsSelectedCommand = new RelayCommand(CallsSelected);
            this.TicketsCommand = new RelayCommand(Tickets);
            this.TicketsSelectedCommand = new RelayCommand(TicketsSelected);
            this.SocialSelectedCommand = new RelayCommand(SocialSelected);
            this.SocialItemSelectedCommand = new RelayCommand(SocialItemSelected);
            this.SocialPostDetailShareCommand = new RelayCommand(SocialPostDetailShare);
            this.ClearAlertsCommand = new RelayCommand(ClearAlerts);
        }

        public AppContent.HomeInfo StaticContent
        {
            get { return this.Get<AppContent.HomeInfo>(); }
            set { this.Set(value); }
        }

        public ObservableCollection<Phone> Phones
        {
            get { return this.Get<ObservableCollection<Phone>>(); }
            set { this.Set(value); }
        }

        public ObservableCollection<Alert> Alerts
        {
            get { return this.Get<ObservableCollection<Alert>>(); }
            set { this.Set(value); }
        }

        public ObservableCollection<Request> Requests
        {
            get { return this.Get<ObservableCollection<Request>>(); }
            set { this.Set(value); }
        }

        public ObservableCollection<RequestItem> RequestItems
        {
            get { return this.Get<ObservableCollection<RequestItem>>(); }
            set { this.Set(value); }
        }

        public ObservableCollection<RequestItem> UserTickets
        {
            get { return this.Get<ObservableCollection<RequestItem>>(); }
            set { this.Set(value); }
        }
   
        public ICommand DialCommand { get; set; }
        public ICommand SettingsCommand { get; set; }
        public ICommand AboutShareCommand { get; set; }
        public ICommand NewRequestCommand { get; set; }
        public ICommand NewRequestCategorySelectedCommand { get; set; }
        public ICommand CallsCommand { get; set; }
        public ICommand CallsSelectedCommand { get; set; }
        public ICommand TicketsCommand { get; set; }
        public ICommand TicketsSelectedCommand { get; set; }
        public ICommand SocialSelectedCommand { get; set; }
        public ICommand SocialItemSelectedCommand { get; set; }
        public ICommand SocialPostDetailShareCommand { get; set; }
        public ICommand NewRegisterCommand { get; set; }
        public ICommand ClearAlertsCommand { get; set; }
        
        private async void ClearAlerts(object param)
        {
            this.IsInProgress = true;

            try
            {
                await AppViewModel.Instance.ClearAlerts();
                this.Alerts.Clear();
            }
            catch
            {
                AppServices.Current.DialogService.Show("Não foi possível limpar a lista de alertas. Por favor tente novamente mais tarde.");
            }

            this.IsInProgress = false;
        }

        private void Dial(object param)
        {
            Phone phone = param as Phone;

            PhoneCallTask phoneCallTask = new PhoneCallTask();

            phoneCallTask.PhoneNumber = phone.Number;
            phoneCallTask.DisplayName = phone.Title;

            phoneCallTask.Show();

            Tracking.SendEvent("Informação", "Ligação", "Ligação Para Central Acionada", 0);

        }

        private void Settings(object param)
        {
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.InAppSettings);
        }

        private void AboutShare(object param)
        {
            
        }

        private void NewRequest(object param)
        {
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.NewRequest);
        }

        private void NewRequestCategorySelected(object param)
        {
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.Request);
        }

        private void Calls(object param)
        {
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.Calls);
        }

        private void CallsSelected(object param)
        {
            
        }

        private void Tickets(object param)
        {
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.Tickets);
        }

        private void TicketsSelected(object param)
        {
            
        }

        private void SocialSelected(object param)
        {
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.Social);
        }

        private void SocialItemSelected(object param)
        {
            
        }

        private void SocialPostDetailShare(object param)
        {
            AppServices.Current.NavigationService.NavigateDirect(ViewsUris.FacebookPostDetail);
        }

        protected async override void Load()
        {
            this.AppContent = AppViewModel.Instance.Properties.AppContent;

            if (this.AppContent != null && this.AppContent.Home != null)
            {
                this.StaticContent = this.AppContent.Home;
            }

            this.IsInProgress = true;

            await base.LoadAsync();

            Byte[] userIdBytes = (Byte[])DeviceExtendedProperties.GetValue("DeviceUniqueId");
            AppViewModel.Instance.Properties.DeviceId = Convert.ToBase64String(userIdBytes);

            this.StaticContent = this.AppContent.Home;

            this.EnforceAppRating();

            if (this.IsConnected)
            {
                await AppViewModel.Instance.Cache.Delete(CacheKeys.Alerts);
                await AppViewModel.Instance.Cache.Delete(CacheKeys.AllRequests);
                await AppViewModel.Instance.Cache.Delete(CacheKeys.UserRequests);
            }

            this.Phones = await AppViewModel.Instance.LoadPhones();
            this.Alerts = await AppViewModel.Instance.LoadAlerts();
            this.Requests = await AppViewModel.Instance.LoadRequests();
            this.RequestItems = await AppViewModel.Instance.LoadAllRequests();
            foreach (var item in this.RequestItems)
            {
                item.SupportersCount = await Api.GetRequestItemSupportersCount(item.Id);
            }
            this.UserTickets = await AppViewModel.Instance.LoadUserRequests();

            Tracking.SendView(ViewsNames.Home);

            this.IsInProgress = false;

            this.OnLoaded();
        }

        #region Rating
        public void EnforceAppRating()
        {
            if (AppViewModel.Instance.Properties.ExecutionsCount % Properties.ExecutionsMinimunRating == 0 &&
                !AppViewModel.Instance.Properties.IsRatingActivated &&
                !AppViewModel.Instance.Properties.IsRatingDeclined)
            {
                this.RatingRequested();
            }
        }

        #endregion
    }
}
